package com.heima.wemedia.Interceptor;

import com.heima.model.wemedia.pojos.WmUser;
import com.heima.utils.thread.WmThreadLocalUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 获取当前操作用户的拦截器
 *
 * @author 10161
 */
@Component
public class WmUserInterceptor implements HandlerInterceptor {

    /**
     * 前置拦截，获取用户id，并且存入到当前线程的threadLocal中
     *
     * @param request
     * @param response
     * @param handler
     * @return
     * @throws Exception
     */
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //todo:把拦截器的bug修复了
        //1.从请求头中获取到userid
        String userId = request.getHeader("userId");
        if (!StringUtils.isBlank(userId)) {
            //userid不为空， 存入当前线程
            WmUser wmUser = new WmUser();
            wmUser.setId(Integer.valueOf(userId));
            WmThreadLocalUtil.setUser(wmUser);
        }
        return true;
    }

    /**
     * 后置拦截，请求的业务已经完成了，清理线程中的数据
     *
     * @param request
     * @param response
     * @param handler
     * @param modelAndView
     * @throws Exception
     */
    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //将当前线程的theadLocal数据清除
        WmThreadLocalUtil.clear();
    }
}
